package com.hula.onion.book.server.spider.platforms.duoyingpuhui;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:49
 *
 * @author shan
 * @version 1.0
 */
@Component
public class DuoYingPuHuiSpiderHelper {

    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form, String token) {

        Map<String, Object> map = new HashMap<>(8);

        map.put("__RequestVerificationToken", token);
        map.put("from", "");
        map.put("returnUrl", "");
        map.put("BackURL", "http://www.duoying.com/");
        map.put("Code", "");
        map.put("device", "");
        map.put("Mobile", form.getUserName());
        map.put("PassWord", form.getPassword());
        return map;

    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {

        try {
            AccountInfo accountInfo = new AccountInfo();
            Document dc = Jsoup.parse(html);

            Element element = dc.selectFirst("div.allAmount");
            Elements els = element.getAllElements();
            String amount = els.text();
            accountInfo.setAmount(new BigDecimal(amount));

            element = dc.selectFirst("dl.equation-additional");
            els = element.getAllElements();
            String totalIntrest = els.get(4).text();
            accountInfo.setTotalIntrest(new BigDecimal(totalIntrest));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }


    /**
     * 解析html
     *
     * @param html
     * @return
     */
    public String parseToken(String html) {

        Document dc = Jsoup.parse(html);

        String element = dc.getElementsByAttributeValue("name", "__RequestVerificationToken").attr("value");

        return element;
    }

}
